package com.base.ticket.service.impl;

import com.base.common.ConfigConstants;
import com.base.common.persistent.dao.TicketMapper;
import com.base.common.persistent.model.Ticket;
import com.base.ticket.service.TicketCommonService;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;

@Service("ticketCommonService")
public class TicketCommonServiceImpl implements TicketCommonService{
	@Resource
	private TicketMapper ticketMapper;

	@Transactional
	@Override
	public int deletePicByCode(String code) throws Exception {
		Ticket ticket = ticketMapper.queryTicketByCode(code);
		String picUrls = ticket.getPicUrls();
		if(picUrls != null && !"".equals(picUrls.trim())) {
			String[] picUrlArr = picUrls.split(";");
			for(int i = 0; i < picUrlArr.length; i++) {
				String[] picUrl = picUrlArr[i].split(ConfigConstants.PROJECT_NAME);
				String realPath = ServletActionContext.getServletContext().getRealPath(
						picUrl[picUrl.length - 1]);
				File file = new File(realPath);
				if(file.exists()) {
					if(file.delete()){
						int n = ticketMapper.updatePicUrlsByCode(code, "");
						if(n == 0) {
							throw new Exception();
						}
						continue;
					} else {
						throw new Exception();
					}
				}
			}
		}
		return 1;
	}

	@Override
	public int evaluateTicket(int score, int ticketId) {
		return ticketMapper.updateScoreById(ticketId, score);
	}

	@Override
	public int queryIdByCode(String code) {
		return ticketMapper.queryTicketByCode(code).getId();
	}

}
